import os
import sys
from pathlib import Path

from app import create_app
from env_config import settings

ROOT = Path(__file__).resolve().parent
SRC = ROOT / "src"
if str(SRC) not in sys.path:
    sys.path.insert(0, str(SRC))

# 容器运行入口
app = create_app()


@app.get("/whoami")
async def whoami():
    import os
    return {"pid": os.getpid()}


if __name__ == '__main__':
    import inspect
    import asyncio
    import uvicorn


    def _parse_bool_env(name, default=False):
        v = os.environ.get(name)
        if v is None:
            return default
        return str(v).strip().lower() in ("1", "true", "yes", "y", "on")


    port = int(os.environ.get("PORT", getattr(settings, "port", 8000)))
    # if env RELOAD set to truthy, use reload (dev). Be careful in PyCharm: reload spawns child process.
    reload_flag = _parse_bool_env("RELOAD", False)

    can_asyncio_run_loop_factory = False
    try:
        sig = inspect.signature(asyncio.run)
        can_asyncio_run_loop_factory = "loop_factory" in sig.parameters
    except Exception:
        can_asyncio_run_loop_factory = False

    if can_asyncio_run_loop_factory:
        # Normal path (most environments)
        uvicorn.run("asgi:app", host="0.0.0.0", port=port, reload=reload_flag, log_level="info")
    else:
        # Fallback: avoid using asyncio.run (some debuggers patch it)
        from uvicorn.config import Config
        from uvicorn.server import Server

        config = Config(app="asgi:app", host="0.0.0.0", port=port, reload=reload_flag, log_level="info")
        server = Server(config=config)
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            loop.run_until_complete(server.serve())
        finally:
            try:
                loop.run_until_complete(loop.shutdown_asyncgens())
            except Exception:
                pass
            loop.close()
